//
//  LocationListViewController.m
//  MagazineShangejie
//
//  Created by cnbizMedia on 16/4/26.
//  Copyright © 2016年 CnbizMedia. All rights reserved.
//

#import "LocationListViewController.h"
#import "AddLocationViewController.h"
#import "Util.h"



@implementation LocationListViewController{

    __weak IBOutlet UITableView *locationListTableView;

    BOOL reloading;
    NSMutableArray *placeData;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self getThePlace];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, 0)];
    view.delegate = self;
    [locationListTableView addSubview:view];
    
    self.refreshHeaderView = view;
    
    [self getThePlace];
}


//获取默认地址信息
-(void)getThePlace{
    
     NSString *token = [UserDefaults objectForKey:@"token"];
    NSLog(@"token   %@",token);
    [[AppAPIClient sharedClient] GET:@"Shop/ListAddress" parameters:@{ @"token":token ,@"status":@"0"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *result = responseObject[@"data"];
        NSLog(@"luntan-data == %@",result);
        if([result isKindOfClass:[NSNull class]] || [result count] == 0){
            return;
        }
        if([result isKindOfClass:[NSNull class]] || [result count] == 0){
            return;
        }
        reloading = NO;
        placeData = [[NSMutableArray alloc]initWithArray:responseObject[@"data"] copyItems:YES];
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:locationListTableView];
        
        [locationListTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD dismiss];
        
    }];
    
    
//    
//    for ( NSDictionary *aPlace in placeData ) {
//        if ([aPlace [@"status"] isEqualToString:@"1"]) {
//            nameAndPhoneNumberLabel.text = [NSString stringWithFormat:@"%@      %@", aPlace[@"consignee"] ,aPlace[@"mobile"]];
//            placeLabel.text = aPlace[@"full_address"];
//            
//            setAPlace.hidden = YES;
//            havePlace = YES;
//        }
//    }
}


#pragma mark - Table view data source


//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    //#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 0;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
        return placeData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    return 60;
 
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
  
        return 10;
     
    }else{
        return 15;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell ;
 
    cell = [tableView dequeueReusableCellWithIdentifier:@"locationListCell" forIndexPath:indexPath];
 
    if (cell==nil) {
  
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"locationListCell"];
 
    }
    
    UILabel*labelb=(UILabel*)[cell.contentView viewWithTag:11];
    UILabel*label=(UILabel*)[cell.contentView viewWithTag:22];
    UIImageView *gouImage = (UIImageView *)[cell.contentView viewWithTag:33];
    
    
    NSDictionary *aPlace = placeData[indexPath.row];
   
    if ([aPlace  [@"status"] isEqualToString:@"0"]) {
       
        gouImage.hidden = YES;

    }
 
    
    labelb.text = [NSString stringWithFormat:@"%@      %@", aPlace[@"consignee"] ,aPlace[@"mobile"]];
    label.text = aPlace[@"full_address"];
 
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    [UserDefaults setInteger:1 forKey:@"add_edit"];//该接口必须传入action参数用来判断所需操作(add=添加=0,edit=编辑=1,delete=删除)
    NSDictionary *aPlace = placeData[indexPath.row];
    [UserDefaults setObject:aPlace forKey:@"aPlace"];
    
    self.hidesBottomBarWhenPushed = YES;
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AddLocationViewController*login=[story instantiateViewControllerWithIdentifier:@"AddLocationViewController"];
    [self.navigationController pushViewController:login animated:YES];
}

- (IBAction)goToAddLocation:(id)sender {
    
    [UserDefaults setInteger:0 forKey:@"add_edit"];//该接口必须传入action参数用来判断所需操作(add=添加=0,edit=编辑=1,delete=删除)
    
    self.hidesBottomBarWhenPushed = YES;
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AddLocationViewController*login=[story instantiateViewControllerWithIdentifier:@"AddLocationViewController"];
    [self.navigationController pushViewController:login animated:YES];

    
}

#pragma mark - UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    int page = (scrollView.contentOffset.x / scrollView.bounds.size.width);
    NSLog(@"page = %d",page);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark RefreshHeaderViewDelegate Methods

-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    if(reloading){
        return;
    }
    reloading=YES;
    [self performSelector:@selector(doneLoadingViewData) withObject:nil afterDelay:0];
}
- (void)doneLoadingViewData{
    
    //  model should call this when its done loading
//    _page=1;
//    isLoading = NO;
//    userData = nil;
//    topArray = [[NSMutableArray alloc]init];
    [self getThePlace];
    
}
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
    return reloading;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
    return [NSDate date];
}

#pragma mark delegate cell
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
//        haoYouPH 必须是  NSMutableArray！！！
        //    action	字符串	add/edit/delete
        //    token	字符串	用户登录token
        //    consignee	字符串	收货人
        //    province	数字	省
        //    city	数字	市
        //    county	数字	区
        //    full_address	字符串	详细地址
        //    mobile	数字	联系电话
        //    status	数字	是否默认收货地址(0=否,1=是)
        
     
        //该接口必须传入action参数用来判断所需操作(add=添加=0,edit=编辑=1,delete=删除)
        
        
        
        
        NSDictionary *aPlace = placeData[indexPath.row];
        
        NSLog(@"aPlace aPlace %@",aPlace);
        
        
        NSString *token = [UserDefaults objectForKey:@"token"];
        
        [[AppAPIClient sharedClient] POST:@"Shop/ChangeAddress" parameters:@{@"action": @"delete",@"token":token,@"id":aPlace[@"id"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject [@"code"] integerValue] == 1) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [placeData removeObjectAtIndex:indexPath.row];
                [locationListTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [locationListTableView reloadData];
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"删除失败"];
            [locationListTableView reloadData];
            NSLog(@"Log:%@",operation.responseString);
        }];
        
        // Delete the row from the data source.
        
        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
@end
